package com.cym.controller;

import java.util.List;

import org.noear.solon.annotation.Controller;
import org.noear.solon.annotation.Inject;
import org.noear.solon.annotation.Mapping;
import org.noear.solon.core.handle.ModelAndView;

import com.cym.model.User;
import com.cym.resp.UserResp;
import com.cym.service.UserService;
import com.cym.sqlhelper.bean.Page;
import com.cym.utils.BaseController;
import com.cym.utils.BeanExtUtil;
import com.cym.utils.JsonResult;

@Controller
@Mapping("/adminPage/user")
public class UserController extends BaseController {
	@Inject
	UserService userService;

	@Mapping("")
	public ModelAndView index(ModelAndView modelAndView, Page pageReq, String keywords) {

		Page<User> pageResp = userService.search(pageReq, keywords);
		Page<UserResp> page = BeanExtUtil.copyPageByProperties(pageResp, UserResp.class);
		for (UserResp userResp : (List<UserResp>) page.getRecords()) {
			userResp.setTypeName(userService.getTypeName(userResp.getType()));
		}

		modelAndView.put("keywords", keywords);
		modelAndView.put("page", page);
		modelAndView.view("/adminPage/user/index.html");
		return modelAndView;
	}

	@Mapping("addOver")

	public JsonResult addOver(User user) {
		User userOrg = userService.getByName(user.getName(), user.getId());
		if (userOrg != null) {
			return renderError("此用户名已存在");
		}

		sqlHelper.insertOrUpdate(user);

		return renderSuccess();
	}

	@Mapping("detail")

	public JsonResult detail(String id) {
		User user = sqlHelper.findById(id, User.class);
		return renderSuccess(user);
	}

	@Mapping("del")

	public JsonResult del(String id) {
		if (userService.hasUserFunction(id)) {
			return renderError("此用户名已存在任务, 不可删除");
		}

		userService.deleteById(id);

		return renderSuccess();
	}

}
